<template>
  <div class="analysis-report-container">
    <!-- 时间维度选择 -->
    <el-card class="filter-card">
      <el-form :inline="true">
        <el-form-item label="时间维度">
          <el-select v-model="timeDimension" @change="handleTimeDimensionChange" style="width: 200px">
            <el-option label="日" :value="1" />
            <el-option label="周" :value="2" />
            <el-option label="月" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleExport">导出报表</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 图表区域 -->
    <el-row :gutter="16" class="chart-row">
      <!-- 报警类型分布 -->
      <el-col :xs="24" :sm="24" :md="12" class="chart-col">
        <el-card class="chart-card">
          <template #header>
            <span>报警类型分布</span>
          </template>
          <div class="chart-body chart-body--medium">
            <ECharts :option="alarmTypeOption" height="100%" />
          </div>
        </el-card>
      </el-col>
      
      <!-- 处理状态占比 -->
      <el-col :xs="24" :sm="24" :md="12" class="chart-col">
        <el-card class="chart-card">
          <template #header>
            <span>处理状态占比</span>
          </template>
          <div class="chart-body chart-body--medium">
            <ECharts :option="statusOption" height="100%" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="16" class="chart-row">
      <!-- 报警趋势 -->
      <el-col :span="24" class="chart-col">
        <el-card class="chart-card">
          <template #header>
            <span>报警趋势变化</span>
          </template>
          <div class="chart-body chart-body--large">
            <ECharts :option="trendOption" height="100%" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="16" class="chart-row">
      <!-- 高频报警点统计 -->
      <el-col :xs="24" :sm="24" :md="12" class="chart-col">
        <el-card class="chart-card">
          <template #header>
            <span>高频报警点TOP5</span>
          </template>
          <div class="chart-body chart-body--medium">
            <ECharts :option="highFreqOption" height="100%" />
          </div>
        </el-card>
      </el-col>
      
      <!-- 处理效率 -->
      <el-col :xs="24" :sm="24" :md="12" class="chart-col">
        <el-card class="chart-card">
          <template #header>
            <span>处理效率统计</span>
          </template>
          <div class="chart-body chart-body--medium">
            <div class="efficiency-info">
              <div class="efficiency-item">
                <div class="efficiency-label">平均处理时长</div>
                <div class="efficiency-value">{{ efficiencyData.avgHandleDuration }} 分钟</div>
                <div class="efficiency-sub">以最近周期统计</div>
              </div>
              <div class="efficiency-item">
                <div class="efficiency-label">处理完成率</div>
                <div class="efficiency-value">{{ formatPercentage(efficiencyData.completionRate) }}%</div>
                <el-progress
                  :percentage="Number(efficiencyData.completionRate) || 0"
                  :stroke-width="12"
                  status="success"
                  :show-text="false"
                />
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 明细列表 -->
    <el-card v-if="selectedTypeData.length > 0">
      <template #header>
        <span>报警类型明细 - {{ selectedTypeName }}</span>
      </template>
      <el-table :data="selectedTypeData" style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="alarmCode" label="报警编码" width="150" />
        <el-table-column prop="sourceName" label="报警来源" width="120" />
        <el-table-column prop="alarmContent" label="报警内容" show-overflow-tooltip />
        <el-table-column prop="triggerTime" label="触发时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.triggerTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import ECharts from '@/components/ECharts/index.vue'
import { 
  getAlarmTypeStats, 
  getAlarmTrend, 
  getHighFreqPoints, 
  getHandleEfficiency,
  getHandleStatusDistribution,
  exportAlarmAnalysisReport
} from '@/api/prod_operate/alarm_management'

const timeDimension = ref(1)
const dateRange = ref([])
const alarmTypeData = ref([])
const trendData = ref([])
const highFreqData = ref([])
const statusData = ref([])
const efficiencyData = ref(createDefaultEfficiency())
const selectedTypeData = ref([])
const selectedTypeName = ref('')

const trendLevelConfig = [
  { key: 'level1', name: '紧急' },
  { key: 'level2', name: '重要' },
  { key: 'level3', name: '一般' }
]

function createDefaultEfficiency () {
  return {
    avgHandleDuration: 0,
    completionRate: 0
  }
}

function normalizeEfficiencyData (payload = {}) {
  const defaults = createDefaultEfficiency()
  const avg = Number(payload.avgHandleDuration)
  const completion = Number(payload.completionRate)
  return {
    avgHandleDuration: Number.isFinite(avg) && avg >= 0 ? avg : defaults.avgHandleDuration,
    completionRate: Number.isFinite(completion)
      ? Math.min(Math.max(completion, 0), 100)
      : defaults.completionRate
  }
}

function formatPercentage (value, fractionDigits = 2) {
  const num = Number(value)
  if (!Number.isFinite(num)) {
    return '0.00'
  }
  return num.toFixed(fractionDigits)
}

const getFileName = (prefix) => {
  const now = new Date()
  const pad = (num) => num.toString().padStart(2, '0')
  return `${prefix}_${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.xlsx`
}

const formatDateToPicker = (date) => {
  const pad = (num) => num.toString().padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}

const setDefaultDateRange = (dimension, force = false) => {
  if (!force && Array.isArray(dateRange.value) && dateRange.value.length === 2) {
    return
  }
  const end = new Date()
  const start = new Date(end)
  if (dimension === 1) {
    start.setDate(end.getDate() - 6)
  } else if (dimension === 2) {
    start.setDate(end.getDate() - 7 * 5 + 1) // 默认最近5周
  } else {
    start.setMonth(end.getMonth() - 5)
    start.setDate(1)
  }
  dateRange.value = [formatDateToPicker(start), formatDateToPicker(end)]
}

const normalizeTrendData = (dataset = []) => {
  const buckets = {}
  dataset.forEach(item => {
    const dateKey = item.statisticDate || '未知日期'
    if (!buckets[dateKey]) {
      buckets[dateKey] = {
        statisticDate: dateKey,
        total: 0,
        level1: 0,
        level2: 0,
        level3: 0
      }
    }
    const count = Number(item.alarmCount) || 0
    const levelKey = `level${item.alarmLevel || ''}`
    if (buckets[dateKey][levelKey] !== undefined) {
      buckets[dateKey][levelKey] += count
    }
    buckets[dateKey].total += count
  })
  return Object.values(buckets).sort((a, b) => a.statisticDate.localeCompare(b.statisticDate))
}

const downloadExcel = async (data, fileName) => {
  if (!data) {
    ElMessage.error('导出失败：返回数据为空')
    return
  }
  const blob = data instanceof Blob ? data : new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  if (blob.type === 'application/json') {
    const text = await blob.text()
    try {
      const err = JSON.parse(text)
      ElMessage.error(err.msg || '导出失败')
    } catch (error) {
      ElMessage.error('导出失败')
    }
    return
  }
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

// 报警类型分布图表配置
const alarmTypeOption = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '报警类型',
        type: 'pie',
        radius: '50%',
        data: alarmTypeData.value.map(item => ({
          value: item.alarmCount,
          name: getAlarmTypeName(item.alarmType)
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
})

// 处理状态占比图表配置
const statusOption = computed(() => {
  const seriesData = statusData.value.length > 0
    ? statusData.value
        .map(item => ({
          value: Number(item.count) || 0,
          name: getStatusName(item.status)
        }))
        .filter(item => item.value > 0)
    : [{ value: 0, name: '暂无数据' }]

  return {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: seriesData
      }
    ]
  }
})

// 报警趋势图表配置
const trendOption = computed(() => {
  const categories = trendData.value.map(item => item.statisticDate)
  const series = [
    {
      name: '总报警次数',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      areaStyle: { opacity: 0.05 },
      data: trendData.value.map(item => item.total || 0)
    }
  ]

  trendLevelConfig.forEach(cfg => {
    series.push({
      name: cfg.name,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      areaStyle: { opacity: 0 },
      data: trendData.value.map(item => item[cfg.key] || 0)
    })
  })

  return {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['总报警次数', ...trendLevelConfig.map(item => item.name)]
    },
    xAxis: {
      type: 'category',
      data: categories
    },
    yAxis: {
      type: 'value'
    },
    series
  }
})

// 高频报警点图表配置
const highFreqOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: highFreqData.value.map(item => item.highFreqPointName)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '报警次数',
        type: 'bar',
        data: highFreqData.value.map(item => item.highFreqCount)
      }
    ]
  }
})

// 时间维度变化
const handleTimeDimensionChange = () => {
  setDefaultDateRange(timeDimension.value, true)
  handleQuery()
}

// 日期变化
const handleDateChange = () => {
  // 日期变化处理
}

// 查询数据
const handleQuery = async () => {
  try {
    setDefaultDateRange(timeDimension.value)
    const startDate = dateRange.value?.[0] || null
    const endDate = dateRange.value?.[1] || null
    
    // 获取报警类型统计
    const typeRes = await getAlarmTypeStats(timeDimension.value, startDate, endDate)
    if (typeRes.code === 200) {
      alarmTypeData.value = typeRes.data || []
    }
    
    // 获取报警趋势
    const trendRes = await getAlarmTrend(timeDimension.value, startDate, endDate)
    if (trendRes.code === 200) {
      trendData.value = normalizeTrendData(trendRes.data || [])
    }

    // 获取处理状态占比
    const statusRes = await getHandleStatusDistribution(startDate, endDate)
    if (statusRes.code === 200) {
      statusData.value = statusRes.data || []
    }
    
    // 获取高频报警点
    const highFreqRes = await getHighFreqPoints(5)
    if (highFreqRes.code === 200) {
      highFreqData.value = highFreqRes.data || []
    }
    
    // 获取处理效率
    const efficiencyRes = await getHandleEfficiency(startDate, endDate)
    efficiencyData.value = efficiencyRes.code === 200
      ? normalizeEfficiencyData(efficiencyRes.data)
      : createDefaultEfficiency()
  } catch (error) {
    ElMessage.error('查询失败：' + error.message)
  }
}

// 导出报表
const handleExport = async () => {
  try {
    const payload = {
      timeDimension: timeDimension.value,
      startDate: dateRange.value?.[0] || null,
      endDate: dateRange.value?.[1] || null,
      limit: 5
    }
    const res = await exportAlarmAnalysisReport(payload)
    await downloadExcel(res, getFileName('报警分析报表'))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败：' + error.message)
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取报警类型名称
const getAlarmTypeName = (type) => {
  const map = { 1: '设备故障', 2: '参数超标', 3: '通讯中断' }
  return map[type] || '未知'
}

// 获取状态标签
const getStatusTag = (status) => {
  const map = { 
    1: 'info', 
    2: 'warning', 
    3: 'warning', 
    4: 'primary', 
    5: 'success', 
    6: 'danger' 
  }
  return map[status] || 'info'
}

// 获取状态名称
const getStatusName = (status) => {
  const map = { 
    1: '未推送', 
    2: '已推送未接收', 
    3: '已接收待处理', 
    4: '处理中', 
    5: '已闭环', 
    6: '已驳回' 
  }
  return map[status] || '未知'
}

onMounted(() => {
  setDefaultDateRange(timeDimension.value, true)
  handleQuery()
})
</script>

<style scoped>
.analysis-report-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background: #f5f7fb;
  min-height: calc(100vh - 160px);
  box-sizing: border-box;
}

.filter-card {
  margin-bottom: 0;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-row:last-of-type {
  margin-bottom: 0;
}

.chart-col {
  display: flex;
}

.chart-card {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.chart-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px 20px 20px;
}

.chart-body {
  flex: 1;
  width: 100%;
}

.chart-body--medium {
  min-height: 320px;
}

.chart-body--large {
  min-height: 420px;
}

.efficiency-info {
  display: flex;
  flex-direction: column;
  gap: 24px;
  justify-content: center;
  height: 100%;
}

.efficiency-item {
  text-align: center;
}

.efficiency-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 12px;
}

.efficiency-value {
  font-size: 30px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.efficiency-sub {
  font-size: 12px;
  color: #c0c4cc;
}

@media screen and (max-width: 991px) {
  .chart-body--medium {
    min-height: 280px;
  }

  .chart-body--large {
    min-height: 360px;
  }
}
</style>

